package com.flyxiaozhu.erp.core.services;

import com.flyxiaozhu.erp.core.utils.SignatureUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.TreeMap;

/**
 * 签名验证配置
 */
@Service
public class SignatureService {

    @Value("${app.sign.field-name.appid}")
    private String fieldNameAppId;

    @Value("${app.sign.field-name.sign}")
    private String fieldNameSign;

    @Value("${app.sign.field-name.time}")
    private String fieldNameTime;

    @Value("${app.sign.field-name.key}")
    private String fieldNameKey;

    @Value("${app.sign.field-name.secret}")
    private String fieldNameSecret;

    public void sign(Map<String, Object> params, Long appid, String key, String secret) {
        params.put(fieldNameAppId, appid);
        params.put(fieldNameTime, System.currentTimeMillis() / 1000);
        params.put(fieldNameKey, key);
        String sign = SignatureUtils.getSign(params, secret, fieldNameSecret);
        params.put(fieldNameSign, sign);
    }

    public boolean verify(HttpServletRequest request, String secret) {
        if (StringUtils.isBlank(request.getParameter(fieldNameAppId)) ||
                StringUtils.isBlank(request.getParameter(fieldNameSign)) ||
                StringUtils.isBlank(request.getParameter(fieldNameTime)) ||
                StringUtils.isBlank(request.getParameter(fieldNameKey))
        ) {
            return false;
        }

        Map<String, String> params = getParams(request);
        String remoteSign = params.get(fieldNameSign);
        params.remove(fieldNameSign);
        if (!SignatureUtils.getSign(params, secret, fieldNameSecret).equalsIgnoreCase(remoteSign)) {
            return false;
        }

        return true;
    }

    private TreeMap<String, String> getParams(HttpServletRequest request) {
        Map<String, String[]> p = request.getParameterMap();
        TreeMap<String, String> result = new TreeMap<>();
        for (String key : p.keySet()) {
            result.put(key, p.get(key)[0]);
        }

        return result;
    }
}
